# 阿里云DashScope API Key配置示例
# 请将此文件重命名为config.py，并填写您的API Key
# 或者在环境变量中设置DASHSCOPE_API_KEY
import os
import dashscope
import ttkbootstrap as ttk

from cryptography.fernet import Fernet

from src.log import HOMEP, SCRIPTP


# 加密密钥
# 使用Fernet.generate_key()生成的有效密钥
ENCRYPT_KEY = b'77N9LIpQodNG4PvreEKzfbOnaxQ_9jEnLsTb7Q3klD0='
FONT_FILE_NAME = 'AlimamaFangYuanTiVF-Thin-2.ttf'
FONT_FAMILY = '阿里妈妈方圆体 VF Medium'


def encrypt(key: str) -> str:
    f = Fernet(ENCRYPT_KEY)
    return f.encrypt(key.encode()).decode()


def decrypt(encrypted_key: str) -> str:
    f = Fernet(ENCRYPT_KEY)
    return f.decrypt(encrypted_key.encode()).decode()


def show_config(root=None):
    try:
        # 创建ttkbootstrap窗口用于输入api_key
        root = ttk.Toplevel(title="API Key 配置", iconphoto=str(SCRIPTP.joinpath("logo.png")), size=(400, 170), resizable=(False, False), alpha=0)
        root.withdraw()
        root.attributes("-alpha", 1.0)

        style = ttk.Style()
        style.configure("TLabel", font=(FONT_FAMILY, 10))
        style.configure("TEntry", font=(FONT_FAMILY, 10))
        style.configure("primary.TButton", font=(FONT_FAMILY, 10))
        style.configure("secondary.TButton", font=(FONT_FAMILY, 10))
        
        api_key_var = ttk.StringVar()

        frame = ttk.Frame(root, padding=20)
        frame.pack(fill="both", expand=True)

        ttk.Label(frame, text="请输入 API Key：").pack(anchor="w", pady=(0, 5))
        entry = ttk.Entry(frame, textvariable=api_key_var, width=40, show="*")
        entry.pack(fill="x", pady=(0, 20))

        def on_confirm():
            key = api_key_var.get().strip()
            if key:
                # 保存key
                HOMEP.joinpath("licence.txt").write_text(encrypt(key))
                root.destroy()
            else:
                ttk.dialogs.Messagebox.show_warning("API Key 不能为空", title="提示")

        ttk.Button(frame, text="取消", command=root.destroy, bootstyle="secondary").place(relx=0.65, rely=0.85, relwidth=0.2, relheight=0.3, anchor="center")
        ttk.Button(frame, text="确认", command=on_confirm, bootstyle="primary").place(relx=0.9, rely=0.85, relwidth=0.2, relheight=0.3, anchor="center")

        # 在左下角放置一个链接标签【如何申请api？】, 点击将打开http://127.0.0.1:9507/note
        link = ttk.Label(frame, text="如何申请API Key？", foreground="#E6A23C", cursor="hand2")
        link.place(relx=0, rely=0.85, relheight=0.3, anchor="w")
        # hover 时改变颜色
        link.bind("<Enter>", lambda e: link.config(foreground="#409EFF"))
        link.bind("<Leave>", lambda e: link.config(foreground="#E6A23C"))
        link.bind("<Button-1>", lambda e: os.system("start http://127.0.0.1:9507/note"))

        def fade_in():
            root.place_window_center()
            root.deiconify()
            root.attributes("-topmost", True)
            entry.focus_set()

        root.after(200, fade_in)
        root.wait_window()
    except Exception as e:
        print(f"配置API Key时出错：{e}")


def check_config(root=None):
    try:
        if HOMEP.joinpath("licence.txt").exists():
            a = HOMEP.joinpath("licence.txt").read_text().strip()
            # a 是aes加密后的字符串，此处要解码
            dashscope.api_key = os.environ.get("DASHSCOPE_API_KEY", decrypt(a))
            return True
        else:
            show_config(root)
    except Exception as e:
        show_config(root)
    try:
        if HOMEP.joinpath("licence.txt").exists():
            a = HOMEP.joinpath("licence.txt").read_text().strip()
            b = decrypt(a)
            print(b)
            # a 是aes加密后的字符串，此处要解码
            dashscope.api_key = os.environ.get("DASHSCOPE_API_KEY", b)
            return True
        else:
            return False
    except Exception as e:
        return False
